<?php
namespace app\modules\merchant\services;

use app\common\services\BaseService;
use app\models\Attribute;
use app\modules\merchant\forms\attribute\AttributeForm;

class AttributeService extends BaseService{

    /**
     * 创建
     * @param AttributeForm $form
     * @return Attribute|bool
     * @throws \Throwable
     */
    public static function create(AttributeForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = new Attribute();
        $model->setAttributes($form->getAttributes(),false);
        if($model->insert() === false){
            return false;
        }
        return $model;
    }

    /**
     * 获取信息
     * @param $merchant_id
     * @param $goods_id
     * @param $id
     * @return array|Attribute|null
     */
    public static function getInfoById($merchant_id,$goods_id,$id){
        $query = Attribute::find();

        if(!empty($merchant_id)){
            $query->andWhere(['merchant_id'=>$merchant_id]);
        }
        if(!empty($goods_id)){
            $query->andWhere(['goods_id'=>$goods_id]);
        }
        if(!empty($id)){
            $query->andWhere(['attr_id'=>$id]);
        }
        return $query->one();
    }

    /**
     * 删除
     * @param $merchant_id
     * @param $goods_id
     */
    public static function delete($merchant_id,$goods_id){
        Attribute::deleteAll(['merchant_id'=>$merchant_id,'goods_id'=>$goods_id]);
    }
}